package model

import (
	"errors"
	"ginblog/utils/errmsg"
	"gorm.io/gorm"
)

type Resources struct {
	BaseModel
	ResourcesName string `gorm:"type:varchar(20);not null;comment:'资源名称'" json:"resources_name"`
	ResourcesUrl  string `gorm:"type:text(512);not null;comment:'资源名称'" json:"resources_url"`
	ResourcesType uint   `gorm:"type:tinyint(3);not null;default 0;comment:'资源类别,0:图片资源，1:视频资源，2:其他资源'" json:"resources_type"`
}

func (r *Resources) SelectTypeRes(pageSize int, pageNum int) []Resources {
	var categoryList []Resources
	err := Db.Where(Resources{ResourcesType: r.ResourcesType}).Limit(pageSize).Offset(pageNum * pageSize).Find(&categoryList).Error
	if err != nil {
		r.SteCodeMsg(errmsg.ERROR)
	}
	return categoryList
}

// SelectAllRes /查询所有资源
func (r *Resources) SelectAllRes(pageSize int, pageNum int) []Resources {
	var categoryList []Resources
	err := Db.Limit(pageSize).Offset(pageNum * pageSize).Find(&categoryList).Error
	if err != nil {
		r.SteCodeMsg(errmsg.ERROR)
	}
	return categoryList
}

// AddRes /保存资源
func (r *Resources) AddRes() bool {
	err := Db.Create(&r).Error
	if err != nil {
		return false
	}
	return true
}

// EditRes /编辑资源
func (r *Resources) EditRes() bool {
	err := Db.Model(&r).Where("id = ? ", r.ID).Omit("Id").Updates(r).Error
	if err != nil {
		return false
	}
	return true
}

// DelRes /删除资源
func (r *Resources) DelRes() bool {
	err := Db.Delete(&Resources{}, r.ID).Error
	if err != nil {
		return false
	}
	return true
}

func (r *Resources) IsResourcesNameRepeat() bool {
	resources := Resources{}
	result := Db.Where(Resources{ResourcesName: r.ResourcesName}).Find(&resources)
	if result.RowsAffected > 0 {
		return true
	}
	return false
}

func (r *Resources) BeforeCreate(tx *gorm.DB) (err error) {
	if r.ResourcesName != "" && r.IsResourcesNameRepeat() {
		err = errors.New(errmsg.GetErrMsg(errmsg.RESOURCES_NAME_IS_USE))
		r.SteCodeMsg(errmsg.RESOURCES_NAME_IS_USE)
	}
	return
}

func (r *Resources) BeforeSave(tx *gorm.DB) (err error) {
	if r.ResourcesName != "" && r.IsResourcesNameRepeat() {
		err = errors.New(errmsg.GetErrMsg(errmsg.RESOURCES_NAME_IS_USE))
		r.SteCodeMsg(errmsg.RESOURCES_NAME_IS_USE)
	}
	return
}
